const app = getApp();

Page({
  data: {
    orderItems: [], // 订单商品列表
    selectedAddress: null, // 选中的地址
    selectedTimeIndex: 0, // 选中的时间索引
    timeOptions: [
      { label: '立即送达', value: '30分钟内' },
    ],
    timePickerRange: [],
    addressList: [], // 地址列表（已不使用列表选择，保留备用）
    showAddressModal: false, // 是否显示地址填写弹窗
    addressForm: { phone: '', floor: '', room: '', remark: '' },
    recentPhones: [],
    showPhoneDropdown: false,
    recentFloors: [],
    showFloorDropdown: false,
    recentRooms: [],
    showRoomDropdown: false,
    totalPrice: 0, // 商品总价
    deliveryFee: 0, // 配送费
    finalPrice: 0, // 最终价格
    buildingInfo: null, // 楼栋信息
    productId: ''
  },

  // 手机号校验：以1开头，第二位3-9，其余为数字，共11位
  isValidPhone(phone) {
    return /^1[3-9]\d{9}$/.test((phone || '').trim());
  },

  onLoad(options) {
    console.log('snacksOrder.onLoad', options);
    
    // 解析传入的参数
    if (options.param) {
      try {
        const param = JSON.parse(decodeURIComponent(options.param));
        console.log('order param:', param);
        
        this.setData({
          orderItems: param.cartItems || [],
          totalPrice: parseFloat(param.totalPrice) || 0,
          buildingInfo: {
            buildingCode: param.buildingCode,
            buildingName: param.buildingName
          },
          productId: param.productId || 'PSnackPickup'
        });
        
        this.prepareTimePickerRange();
        this.loadBuildingDeliveryFee(); // 先加载配送费
        this.calculateFinalPrice();
        this.loadLastDeliveryInfo(); // 加载上次收货信息
      } catch (e) {
        console.error('parse order param failed:', e);
        wx.showToast({
          title: '参数错误',
          icon: 'none'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    } else {
      wx.showToast({
        title: '缺少订单信息',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 加载上次收货信息
  loadLastDeliveryInfo() {
    try {
      const lastDeliveryInfo = wx.getStorageSync('lastDeliveryInfo');
      if (lastDeliveryInfo && lastDeliveryInfo.phone) {
        console.log('找到上次收货信息:', lastDeliveryInfo);
        
        // 自动填充地址表单信息
        this.setData({
          'addressForm.phone': lastDeliveryInfo.phone,
          'addressForm.floor': lastDeliveryInfo.floor,
          'addressForm.room': lastDeliveryInfo.room,
          'addressForm.remark': lastDeliveryInfo.remark || ''
        });
        
        // 不在这里显示提示，改为在用户点击选择地址时显示
      }
    } catch (e) {
      console.warn('加载上次收货信息失败:', e);
    }
  },

  // 选择地址
  onSelectAddress() {
    // 检查是否有自动填充的地址信息
    const { addressForm } = this.data;
    if (addressForm.phone && addressForm.floor && addressForm.room) {
      wx.showToast({
        title: '已自动填充上次收货地址',
        icon: 'none',
        duration: 2000
      });
    }
    
    this.setData({
      showAddressModal: true
    });
  },

  // 关闭地址选择弹窗
  onCloseAddressModal() {
    this.setData({
      showAddressModal: false
    });
  },

  // 地址表单输入
  onAddressPhoneInput(e) {
    this.setData({ 'addressForm.phone': e.detail.value.trim(), showPhoneDropdown: true });
  },
  onAddressPhoneFocus() {
    try {
      const arr = wx.getStorageSync('userRecentPhone') || [];
      if (Array.isArray(arr)) {
        const limited = arr.filter(Boolean).slice(0, 3);
        const recent = limited[0] || '';
        const current = this.data.addressForm.phone || '';
        const nextPhone = current ? current : recent;
        this.setData({ recentPhones: limited, showPhoneDropdown: true });
        if (nextPhone && !current) {
          this.setData({ 'addressForm.phone': nextPhone });
        }
      }
    } catch (e) {
      console.warn('read userRecentPhone failed', e);
    }
  },
  onAddressPhoneBlur() {
    const phone = (this.data.addressForm.phone || '').trim();
    // 延迟收起，避免点击候选项时丢失点击
    setTimeout(() => {
      this.setData({ showPhoneDropdown: false });
    }, 150);
    if (phone && !this.isValidPhone(phone)) {
      wx.showToast({ title: '手机号格式不正确', icon: 'none', duration: 1500 });
    }
  },
  onSelectRecentPhone(e) {
    const phone = e.currentTarget.dataset.phone || '';
    if (phone) {
      this.setData({ 'addressForm.phone': phone, showPhoneDropdown: false });
    }
  },
  onAddressFloorInput(e) {
    const value = e.detail.value.trim();
    this.setData({ 'addressForm.floor': value });
    // 实时校验楼层
    if (value) {
      const num = parseInt(value, 10);
      if (isNaN(num) || num < -5 || num > 10) {
        wx.showToast({
          title: '楼层范围：-5到10',
          icon: 'none',
          duration: 1500
        });
      }
    }
  },
  onAddressFloorFocus() {
    try {
      const arr = wx.getStorageSync('userRecentFloor') || [];
      if (Array.isArray(arr)) {
        const limited = arr.filter(Boolean).slice(0, 3);
        const recent = limited[0] || '';
        const current = this.data.addressForm.floor || '';
        const nextValue = current ? current : recent;
        this.setData({ recentFloors: limited, showFloorDropdown: true });
        if (nextValue && !current) {
          this.setData({ 'addressForm.floor': nextValue });
        }
      }
    } catch (e) {
      console.warn('read userRecentFloor failed', e);
    }
  },
  onAddressFloorBlur() {
    setTimeout(() => {
      this.setData({ showFloorDropdown: false });
    }, 150);
  },
  onSelectRecentFloor(e) {
    const value = e.currentTarget.dataset.value || '';
    if (value) {
      this.setData({ 'addressForm.floor': value, showFloorDropdown: false });
    }
  },
  onAddressRoomInput(e) {
    this.setData({ 'addressForm.room': e.detail.value.trim() });
  },
  onAddressRoomFocus() {
    try {
      const arr = wx.getStorageSync('userRecentRoom') || [];
      if (Array.isArray(arr)) {
        const limited = arr.filter(Boolean).slice(0, 3);
        const recent = limited[0] || '';
        const current = this.data.addressForm.room || '';
        const nextValue = current ? current : recent;
        this.setData({ recentRooms: limited, showRoomDropdown: true });
        if (nextValue && !current) {
          this.setData({ 'addressForm.room': nextValue });
        }
      }
    } catch (e) {
      console.warn('read userRecentRoom failed', e);
    }
  },
  onAddressRoomBlur() {
    setTimeout(() => {
      this.setData({ showRoomDropdown: false });
    }, 150);
  },
  onSelectRecentRoom(e) {
    const value = e.currentTarget.dataset.value || '';
    if (value) {
      this.setData({ 'addressForm.room': value, showRoomDropdown: false });
    }
  },

  onAddressRemarkInput(e) {
    this.setData({ 'addressForm.remark': e.detail.value });
  },

  // 确认地址
  onConfirmAddress() {
    const { phone, floor, room, remark } = this.data.addressForm;
    if (!phone) {
      wx.showToast({ title: '请填写联系电话', icon: 'none' });
      return;
    }
    if (!this.isValidPhone(phone)) {
      wx.showToast({ title: '手机号格式不正确', icon: 'none' });
      return;
    }
    if (!floor || !room) {
      wx.showToast({ title: '请填写楼层与房间号', icon: 'none' });
      return;
    }
    // 校验楼层范围
    const floorNum = parseInt(floor, 10);
    if (isNaN(floorNum) || floorNum < -5 || floorNum > 10) {
      wx.showToast({ title: '楼层范围：-5到10', icon: 'none' });
      return;
    }
    // 写回最近使用缓存（phone/floor/room）
    try {
      const writeRecent = (key, value) => {
        const trimmed = (value || '').trim();
        if (!trimmed) return;
        let arr = wx.getStorageSync(key) || [];
        if (!Array.isArray(arr)) arr = [];
        // 去重将本次置顶
        arr = [trimmed, ...arr.filter(v => v && v !== trimmed)];
        wx.setStorageSync(key, arr.slice(0, 3));
      };
      writeRecent('userRecentPhone', phone);
      writeRecent('userRecentFloor', String(floor));
      writeRecent('userRecentRoom', String(room));
    } catch (e) {
      console.warn('write recent cache failed', e);
    }
    const selectedAddress = { phone, floor, room, remark };
    this.setData({ selectedAddress, showAddressModal: false });
  },

  // 选择送达时间
  onTimePickerChange(e) {
    const index = Number(e.detail.value || 0);
    this.setData({ selectedTimeIndex: index });
  },

  prepareTimePickerRange() {
    const range = (this.data.timeOptions || []).map(opt => `${opt.label}（${opt.value}）`);
    this.setData({ timePickerRange: range });
  },

  // 计算最终价格
  calculateFinalPrice() {
    const totalPrice = parseFloat(this.data.totalPrice) || 0;
    // 配送费将从楼栋信息中获取，这里先使用默认值
    const deliveryFee = parseFloat(this.data.deliveryFee) || 2.0;
    const finalPrice = totalPrice + deliveryFee;
    
    this.setData({
      deliveryFee: deliveryFee.toFixed(1),
      finalPrice: finalPrice.toFixed(1)
    });
  },

  // 加载楼栋配送费信息
  loadBuildingDeliveryFee() {
    if (!this.data.buildingInfo || !this.data.buildingInfo.buildingCode) {
      console.warn('buildingInfo not available for delivery fee loading');
      return;
    }

    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        getBuildingDeliveryFeeRequest: {
          schoolCode: 'xue_chang_zhi_ye', // 这里应该从buildingInfo中获取，暂时硬编码
          buildingCode: this.data.buildingInfo.buildingCode
        }
      },
      success: (res) => {
        console.log('loadBuildingDeliveryFee result:', res);
        if (res.result?.code === 200) {
          const deliveryFee = parseFloat(res.result.data.deliveryFee) || 2.0;
          this.setData({
            deliveryFee: deliveryFee
          });
          // 重新计算最终价格
          this.calculateFinalPrice();
        } else {
          console.warn('Failed to load delivery fee, using default:', res.result?.message);
          // 使用默认配送费
          this.calculateFinalPrice();
        }
      },
      fail: (err) => {
        console.error('loadBuildingDeliveryFee failed:', err);
        // 使用默认配送费
        this.calculateFinalPrice();
      }
    });
  },

  // 提交订单
  async onSubmitOrder() {
    if (!this.data.selectedAddress) {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none'
      });
      return;
    }

    if (this.data.orderItems.length === 0) {
      wx.showToast({
        title: '购物车为空',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({ title: '提交中...' });

    const selectedAddress = wx.getStorageSync('selectedAddress');
    let schoolCode = "xue_chang_zhi_ye"; // 默认值

    // 如果缓存中有选中的地址，使用其addressCode作为schoolCode
    if (selectedAddress && selectedAddress.addressCode) {
      schoolCode = selectedAddress.addressCode;
    }

    try {
      // 构建订单数据
      const orderData = {
        productId: this.data.productId,
        schoolCode: schoolCode,
        buildingCode: this.data.buildingInfo.buildingCode,
        buildingName: this.data.buildingInfo.buildingName,
        address: this.data.selectedAddress,
        deliveryTime: this.data.timeOptions[this.data.selectedTimeIndex],
        items: this.data.orderItems,
        totalPrice: this.data.totalPrice,
        deliveryFee: this.data.deliveryFee,
        finalPrice: this.data.finalPrice
      };

      console.log('submit snacks order:', orderData);

      // 调用零食下单接口
      const res = await wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: {
          snacksCreateOrderRequest: orderData
        }
      });

      console.log('snacksCreateOrder result:', res);
      wx.hideLoading();

      if (res.result?.code === 200) {
        const data = res.result.data;
        
        // 处理支付
        if (data.nonceStr && data.package && data.paySign) {
          try {
            const orderId = await this.handlePayment(data);
            await this.handlePaySuccess(orderId);
          } catch (payErr) {
            console.error('支付流程异常', payErr);
            wx.showToast({
              title: '支付失败',
              icon: 'none'
            });
          }
        } else {
          // 免费订单，直接成功
          await this.handlePaySuccess(data.orderId);
        }
      } else {
        wx.showToast({
          title: res.result?.message || '下单失败',
          icon: 'none'
        });
      }
    } catch (err) {
      console.error('snacksCreateOrder failed:', err);
      wx.hideLoading();
      wx.showToast({
        title: '下单失败',
        icon: 'none'
      });
    }
  },

  // 处理支付
  async handlePayment(paymentData) {
    return new Promise((resolve, reject) => {
      wx.requestPayment({
        timeStamp: paymentData.timeStamp,
        nonceStr: paymentData.nonceStr,
        package: paymentData.package,
        signType: paymentData.signType,
        paySign: paymentData.paySign,
        success: (res) => {
          console.log('支付成功', res);
          resolve(paymentData.orderId);
        },
        fail: (err) => {
          console.error('支付失败', err);
          reject(err);
        }
      });
    });
  },

  // 支付成功后处理
  async handlePaySuccess(orderId) {
    try {
      console.log('handlePaySuccess.paySuccessCallback.params: ', { orderId });
      
      const paySuccessCallBackRes = await wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: {
          paySuccessCallbackRequest: { orderId: orderId }
        }
      });
      
      console.log('handlePaySuccess.paySuccessCallback.res: ', JSON.stringify(paySuccessCallBackRes));
      
      // 保存收货信息到本地缓存
      const deliveryInfo = {
        phone: this.data.selectedAddress.phone,
        floor: this.data.selectedAddress.floor,
        room: this.data.selectedAddress.room,
        remark: this.data.selectedAddress.remark || '',
        lastUsedTime: new Date().getTime()
      };
      
      // 保存到本地存储，用于下次快速填写
      wx.setStorageSync('lastDeliveryInfo', deliveryInfo);
      
      // 清除购物车数据（按当前楼栋维度）
      try {
        const productId = this.data.productId || 'PSnackPickup';
        const buildingCode = this.data?.buildingInfo?.buildingCode;
        if (productId && buildingCode) {
          const cartKey = `cart_${productId}_${buildingCode}`;
          wx.removeStorageSync(cartKey);
        }
      } catch (e) {
        console.warn('remove per-building cart failed', e);
      }
      // 兼容旧版通用键清理
      wx.removeStorageSync('snacksCartItems');
      wx.removeStorageSync('snacksTotalPrice');
      
      wx.showToast({
        title: '下单成功',
        icon: 'success'
      });
      
      // 跳转到订单列表
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/orderList1/index',
        });
      }, 1500);
    } catch (err) {
      console.error('支付成功回调失败', err);
      wx.showToast({
        title: '订单处理中，请稍后查看订单状态',
        icon: 'none'
      });
    }
  },

  // 防止弹窗内点击冒泡
  noop() {}
});
